<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>账号</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-button type="primary" class="fr fr_btn"  @click="addInternalUserFlag = true">添加内部用户</el-button>
        <div class="container">
            <!--@change="changePhone"-->

            <el-input
                clearable
                style="width: 300px;margin-bottom: 20px;"
                v-model="memberName"
                @change="changeName"
                placeholder="输入姓名" class="checkCoupon_input" >
                <el-button
                    slot="append"
                    icon="el-icon-search"
                    type="success"
                    circle
                    @click="searchName(memberName)"
                ></el-button>
            </el-input>
            <el-table v-if="activeShow" :data="userList" border style="width: 100%"  ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column prop="user.nick" label="账号" sortable  >
                </el-table-column>
                <el-table-column prop="user.mobileNumber" label="手机号" sortable >
                </el-table-column>
                <el-table-column prop="role.roleInfo" label="角色" sortable >
                </el-table-column>
                <!--<el-table-column prop="user.status" label="状态">-->
                    <!--<template slot-scope="scope">-->
                        <!--<span v-if="scope.row.user.status == 'NORMAL'">正常</span>-->
                    <!--</template>-->
                <!--</el-table-column>-->
                <el-table-column label="操作" width="270">
                    <template slot-scope="scope">
                        <el-button size="small" @click="userRole(scope.row)">修改角色</el-button>
                        <!--<el-button size="small" @click="userStore(scope.row)">修改门店</el-button>-->
                        <el-button v-if="scope.row.status == 'NORMAL' || scope.row.user.status == 'NORMAL'" size="small" type="danger" @click="addExternalUser(scope.row)">停用</el-button>
                        <el-button v-else size="small" type="success" @click="changeStatus(scope.row)">启用</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :page-size="size"
                    layout="prev, pager, next"
                    :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 修改角色弹出框 -->
        <el-dialog title="修改角色" :visible.sync="changeRoleVisible" width="500px">
            <el-select v-model="roleId" placeholder="请选择">
                <el-option v-for="item in allRolesIdList" :key="item.id"  :label="item.roleName" :value="item.id">
                </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button @click="changeRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeRole()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改门店弹出框 -->
        <el-dialog title="修改门店" :visible.sync="changeStoreVisible" width="500px">

            <el-checkbox-group v-model="checkedShop">
                <el-checkbox v-for="item in allShop" :label="item.id" :key="item.id">{{item.shopName}}</el-checkbox>
            </el-checkbox-group>

            <span slot="footer" class="dialog-footer">
                <el-button @click="changeStoreVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeShop()">确 定</el-button>
            </span>
        </el-dialog>

        <!--添加内部用户-->
        <el-dialog title="添加内部用户" :visible.sync="addInternalUserFlag" width="500px">
            <el-input v-model="internalUserName" placeholder="用户姓名" style="margin-bottom: 20px"></el-input>
            <el-input v-model="internalUserMobile" placeholder="用户手机号码"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addInternalUserFlag = false">取 消</el-button>
                <el-button type="primary" @click="addInternalUser()">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import {allstore , userBindShop ,user ,userSope ,myRole ,roles} from '../api/api'
import {
    storeAsGet,
    storeAsPost,
    storeAsPut,
    attachments
} from '../api/api';
import {tool_confirm} from '../tool/tool'
    export default {
        data() {
            return {
                memberName: '',
                Token:localStorage.getItem('token'),
                url: './static/vuetable.json',
                tableData: [],
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                internalUserName: '',
                internalUserMobile: '',
                del_list: [],
                is_search: false,
                changeRoleVisible: false,
                addInternalUserFlag: false,
                changeStoreVisible: false,
                idx: -1,
                dateValue:'',
                roleId:'',
                checkedShop: [],//已经绑定的门店
                allShop:[],//所有门店
                page:0,//默认展示第一页
                size:10,
                total:0,
                userList:[],
                changeId:'',//要修改的用户id
                allRolesIdList:[],
                userStatus: '',
                activeShow: true,
            }
        },
        mounted(){
            this.getSore()
            this.getList()
            this.getRole()
        },
        methods: {
            userStore(row){//获取该用户绑定的门店
                let id = row.user.id
                this.changeId =row.user.id
                this.changeStoreVisible= true
                userSope({
                     userId:id
                 }).then(res => {
                    let arr = res.data.content.shopUserRelationList
                    let shopID = []
                    for(var i = 0;i<arr.length;i++){
                        shopID.push(arr[i].shop.id)
                    }
                    this.checkedShop = shopID
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                })
            },
            getSore(){//获取门店列表
                 allstore({
                     direction:'DESC',
                     propertys:'id',
                     status:'NORMAL'
                 }).then(res => {
                     this.allShop = res.data.content.list
                }).catch(errors=>{
                     this.$message.error(errors.response.data.detail)
                 })
            },
            getList(){//获取用户及角色列表
                this.activeShow = false;
                this.$nextTick(function () {
                    this.activeShow = true;
                })
                user({
                    page:this.page,
                    size:this.size,
                    direction:'DESC',
                    propertys:'createdTime',
                    name: this.memberName
                 }).then(res => {
                     this.userList = res.data.content.page.content;
                     this.total = res.data.content.page.totalElements;
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                })
            },
            changeShop(){//给选中的用户绑定门店 或修改门店
                let _this  = this
                 $.ajax({
                    url:_this.$ajaxBase+'shop/user/relation/multiple?userId='+_this.changeId,
                    type: 'POST',
                    async: false,
                    headers:{
                            "Access-Token":_this.Token,
                            'Content-Type': 'application/json'
                        },
                    data:JSON.stringify(_this.checkedShop),
                    success: function (res) {
                        _this.$message({
                            message: '门店修改成功',
                            type: 'success'
                        });
                        _this.changeStoreVisible= false
                    },
                    error: function (error) {
                        _this.$message.error('门店修改失败');
                    }
                });
            },
            getRole(){//获取角色列表
                let arr= [];
                 roles({
                     direction:'DESC',
                     propertys:'roleName'
                 }).then(res => {
                     console.log(res.data.content.list,"res")
                     res.data.content.list.forEach(function(val){
                         if(val.roleName !== 'admin'){
                             arr.push(val)
                         }
                     });
                     this.allRolesIdList = arr
                }).catch(errors=>{
                     this.$message.error(errors.response.data.detail)
                 })
            },
            userRole(row){//获取该用户绑定的角色
                let id = row.user.id
                this.changeId =row.user.id
                this.changeRoleVisible = true;
                myRole({
                     userId:id
                 }).then(res => {
                    this.roleId = res.data.content.role.id
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                })
            },
            changeRole(){//给选中的用户修改角色
                let _this = this
                 _this.$axios.post('role/user/relation/multiple?userId='+_this.changeId+'&roleId='+_this.roleId)
                    .then(function (response) {
                        _this.$message({
                            message: '角色修改权限成功',
                            type: 'success'
                        });
                        _this.getList();
                    }).catch(errors=>{
                     _this.$message.error(errors.response.data.detail)
                 })
                _this.changeRoleVisible = false;

            },
            //添加内部用户
            addInternalUser(){
                let that = this;
                console.log(that.internalUserMobile)
                storeAsPut('/users/userType?userType=INTERNAL&mobileNumber=' + that.internalUserMobile+'&name='+that.internalUserName).then(function(res){
                    console.log(res)
                    that.$message({
                        message: '添加内部用户成功！',
                        type: 'success'
                    });
                    that.getList()
                }).catch(errors=>{
                    that.$message.error(errors.response.data.detail)
                })
                that.addInternalUserFlag = false;
            },
            //内部转外部用户
            addExternalUser(e){
                let that = this;
                console.log(e.user.id)
                tool_confirm(this,'是否要修改状态？').then(res => {
                    storeAsPut('users/userType/userId?userType=EXTERNAL&userId=' + e.user.id).then(function(res){
                        console.log(res)
                        that.$message({
                            message: '已停用该用户！',
                            type: 'success'
                        });
                        that.getList()
                    })
                }).catch(() => {
                    console.log('取消')
                });

            },
            changeName(val){
                console.log(val,"290")
                if(val == ''){
                    this.getList()
                }
            },
            searchName(val){
                this.memberName = val;
                this.getList();
            },
            // 分页导航
            handleCurrentChange(val) {
                this.page = val-1;
                console.log(val)
                 this.getList();
            },
            changeStatus(row){
                let status
                if(row.user.status == 'NORMAL'){
                    status = 'DISABLED'
                }else{
                     status = 'NORMAL'
                }
                let id = row.user.id
                let _this = this
                 _this.$axios.put('users/status?status='+status+'&userId='+id)
                .then(function (response) {
                    _this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                    _this.getList()
                }).catch(errors=>{
                     _this.$message.error(errors.response.data.detail)
                 })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            }


        }
    }

</script>

<style scoped>
    .fr_btn{
        margin-top:-40px!important;
    }
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .el-select{
        width: 100%;
    }
    .el-dialog__body{
        max-height: 370px;
        overflow: auto;
    }
</style>
